/****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) Microsoft Open Technologies, Inc.

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/

#include "MainMenuScene.h"
#include "MainGameScene.h"
#include "GameDimensions.h"
#include "AppDelegate.h"
#include "UserScores.h"

MainMenuScene::MainMenuScene():MyScene()
{
//    ctor
}

MainMenuScene::~MainMenuScene()
{
//      dtor
}


bool MainMenuScene::init()
{
    CCLayer *layer=CCLayer::create();
    addChild(layer);

    AppDelegate* app=AppDelegate::getApplication();
    const GameDimensions* gameDimension=app->getGameDimensions();
    CCLog("game window = %d x %d",gameDimension->width,gameDimension->height);

    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
    //CCLog("----%d,%d",gameDimension->gwLeft,gameDimension->gwTop);

    int x0=gameDimension->gwLeft+ origin.x,
    y0=gameDimension->gwTop+ origin.y;
    int w=gameDimension->width,h=gameDimension->height;

    // Add background
    CCSprite* pSprite = CCSprite::create("background-main.png");
    pSprite->setPosition(ccp(x0+w/2, y0+h/2));
    layer->addChild(pSprite, 0);

    // Add menu items
    CCMenu* pMenu = CCMenu::create();
    pMenu->setPosition(CCPointZero);
    layer->addChild(pMenu, 1);

    // Add items from bottom to top
    const char* labelTexts[5]={"Exit","Scores","Difficulty","New Game","Continue"};
    SEL_MenuHandler handler[5]={
        menu_selector(MainMenuScene::menuCloseCallback)
        ,menu_selector(MainMenuScene::menuScoresCallback)
        ,menu_selector(MainMenuScene::menuDiffcultyCallback)
        ,menu_selector(MainMenuScene::menuNewGameCallback)
        ,menu_selector(MainMenuScene::menuContinueCallback)
    };

    int hb=(int)(gameDimension->ratio*100);
    for(int i=0;i<5;i++){
        int fs=(int)(gameDimension->mainMenuHeight*0.5);
        CCLabelTTF* label = CCLabelTTF::create(labelTexts[i], "fonts/Marker Felt.ttf",fs);
        //label->setScale(0.5);
        label->setColor(ccc3(255,255,0));
        CCMenuItemLabel* item = CCMenuItemLabel::create(label, this,handler[i]);
        float xi=gameDimension->mainMenuX,yi=y0 +hb+ gameDimension->mainMenuHeight*(i+0.5);
        item->setPosition(ccp(xi,yi));
        //
        pMenu->addChild(item,0);
    }
    //
    drawDebugBox();

    return true;
}

void MainMenuScene::menuContinueCallback()
{
    MainGameScene::useSaved=true;
    MyScene* game=MainGameScene::create();
    goScene(game);
}

void MainMenuScene::menuDiffcultyCallback()
{
    MyScene* difs=DifficultyMenuScene::create();
    goScene(difs);
    //CCDirector::sharedDirector()->pushScene( CCTransitionPageTurn::create(0.5f, difs,false) );
}

void MainMenuScene::menuNewGameCallback()
{
    MainGameScene::useSaved=false;
    MyScene* game=MainGameScene::create();
    //CCDirector::sharedDirector()->pushScene( CCTransitionPageTurn::create(0.5f, game,false) );
    goScene(game);
}

void MainMenuScene::menuScoresCallback()
{
    MyScene* game=ScoresMenuScene::create();
    goScene(game);
    //CCDirector::sharedDirector()->pushScene( CCTransitionPageTurn::create(0.5f, game,false) );
}


void MainMenuScene::menuCloseCallback()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
    CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
    CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
#endif
}

//difficulty

bool DifficultyMenuScene::init(){
    //
    AppDelegate* app=AppDelegate::getApplication();
    const GameDimensions* gameDimension=app->getGameDimensions();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
    //The count of difficulty
    int n=6;
    int x0=origin.x+gameDimension->gwCx;
    int y0=origin.y+(int)((100)*gameDimension->ratio);
    int yc=origin.y+gameDimension->gwCy;
    int hm=(int)((800-100-160)*gameDimension->ratio/(n+2));

    //load data
    CCUserDefault* save=CCUserDefault::sharedUserDefault();
    int lastgs=save->getIntegerForKey("game_diff");
    if(lastgs>=3 && lastgs<(3+n)){
        difficulty=lastgs;
    }else{
        difficulty=3;
    }
    CCLog("last difficulty=%d",difficulty);

    //Add background
    CCSprite* bk=CCSprite::create("background-main.png"/*,CCRect(0,0,480,800)*/);
    //bk->setScale(gameDimension->ratio);
    bk->setPosition(ccp(x0,yc));
    addChild(bk,0);
    //Add menu
    CCMenu* pMenu = CCMenu::create();
    pMenu->setPosition(CCPointZero);
    addChild(pMenu, 1);

    //Add menu items
    //Add back
    const char fnt[]="fonts/my-font.fnt";
    CCLabelBMFont* lback = CCLabelBMFont::create("Back", fnt);
    CCMenuItemLabel* mback = CCMenuItemLabel::create(lback, this,
        menu_selector(DifficultyMenuScene::menuBackCallback));
    //float xi=gameDimension->mainMenuX,yi=y0 + gameDimension->mainMenuHeight*(i+0.5);
    mback->setPosition(ccp(x0,y0+hm/2));
    pMenu->addChild(mback,0);

    //Add difficultys
    for(int i=0;i<n;i++){
        int gs=3+n-1-i; ///game size
        char str[10];
        sprintf(str,"%d x %d",gs,gs);
        CCLabelBMFont* ldifs = CCLabelBMFont::create(str, fnt);
        CCMenuItemLabel* mdifs = CCMenuItemLabel::create(ldifs);
        mdifs->initWithTarget(mdifs,menu_selector(DifficultyMenuScene::menuDifficultyCallback));
        //float xi=gameDimension->mainMenuX,yi=y0 + gameDimension->mainMenuHeight*(i+0.5);
        mdifs->setPosition(ccp(x0,y0+hm/2+(i+1)*hm));
        mdifs->setTag(gs);
        if(gs==difficulty){
            mdifs->selected();
        }
        pMenu->addChild(mdifs,0);
    }
    CCLabelBMFont* ltitle = CCLabelBMFont::create("Select Difficulty", fnt);
    ltitle->setPosition(ccp(x0,y0+hm/2+(n+1)*hm));
    ltitle->setColor(ccc3(255,0,0));
    addChild(ltitle,1);


    return true;


}

void DifficultyMenuScene::onExit(){
    //
    MyScene::onExit();
}

void DifficultyMenuScene::menuBackCallback(){
    //CCDirector::sharedDirector()->popScene();
    backToMain();
}

void DifficultyMenuScene::menuDifficultyCallback(CCObject* obj){
    CCNode* node=(CCNode*)obj;
    int gs=node->getTag();
    difficulty=gs;
    //CCLog("...%d, dif=%d",gs,difficulty);

    //save data
    CCUserDefault* save=CCUserDefault::sharedUserDefault();
    CCLog("difficuty = %d",difficulty);
    save->setIntegerForKey("game_diff",difficulty);
    save->flush();

    //exit
    //CCDirector::sharedDirector()->popScene();
    backToMain();
}


//Sorces

bool ScoresMenuScene::init(){
    AppDelegate* app=AppDelegate::getApplication();
    const GameDimensions* gameDimension=app->getGameDimensions();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
    //The count of difficulty
    int n=10;
    int x0=origin.x+gameDimension->gwCx;
    int y0=origin.y+gameDimension->height-(int)((160)*gameDimension->ratio);
    int yc=origin.y+gameDimension->gwCy;
    int hm=(int)((800-100-160)*gameDimension->ratio/(n+2));
    //
    //Add background
    CCSprite* bk=CCSprite::create("background-main.png"/*,CCRect(0,0,480,800)*/);
    //bk->setScale(gameDimension->ratio);
    bk->setPosition(ccp(x0,yc));
    addChild(bk,0);
    //Add menu
    CCMenu* pMenu = CCMenu::create();
    pMenu->setPosition(CCPointZero);
    addChild(pMenu, 1);

    //Add menu items
    //Add back
    float scale=0.4;

    const char fnt[]="fonts/my-font.fnt";
    CCLabelBMFont* lback = CCLabelBMFont::create("Back", fnt);
    CCMenuItemLabel* mback = CCMenuItemLabel::create(lback, this,
        menu_selector(ScoresMenuScene::menuBackCallback));
    //float xi=gameDimension->mainMenuX,yi=y0 + gameDimension->mainMenuHeight*(i+0.5);
    mback->setPosition(ccp(x0,y0-hm/2-(n+1)*hm));
    pMenu->addChild(mback,0);



    //Add title
    //const char fnt[]="fonts/my-font.fnt";
    CCLabelBMFont* ltitle = CCLabelBMFont::create("    Date             Diff   Mov  Time    Score", fnt);
    ltitle->setPosition(ccp(x0,y0-hm/2));
    ltitle->setScale(scale);
    ltitle->setColor(ccc3(255,0,0));
    addChild(ltitle,1);

    //Add scores data
    UserScores scores;
    list<RecordData> ls=scores.getData();
    int i=0;
    for(list<RecordData>::iterator it=ls.begin();it!=ls.end();++it){
        RecordData dd=*it;
        char str[80];
        char tAll[15];
        strftime(tAll,sizeof(tAll),"%Y/%m/%d ",localtime(&(dd.date)));
        int mm=dd.time/60;
        int ss=dd.time%60;
        sprintf(str,"%10s% 6d% 10d  %02d:%02d% 10d",tAll,dd.diff,dd.mov,mm,ss,dd.score);
        CCLog("%s",str);
        //
        CCLabelBMFont* lab = CCLabelBMFont::create(str, fnt);
        lab->setPosition(ccp(x0,y0-hm/2-(i+1)*hm));
        lab->setScale(scale);
        lab->setColor(ccc3(255,255,0));
        addChild(lab,1);
        i++;
    }

    return true;

}

void ScoresMenuScene::menuBackCallback(){
    //exit
    backToMain();
    //CCDirector::sharedDirector()->popScene();
}


